package com.itheima.app.controller;

import com.itheima.app.manager.UserManager;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private UserManager userManager;

    //保存用户，返回id
    @PostMapping("/save")
    public Long save(@RequestBody User user) {
        return userManager.save(user);
    }

    //根据手机号查询用户     前端传入的是json数据    所以需要@RequestBody注解
    //发送短信验证码
    @PostMapping("/user/login")
    public User sendSms(@RequestBody Map<String,String> map) {
        //1.接收参数
        String phone = map.get("phone");
        //2.调用manager
        return userManager.sendSms(phone);
    }
    //req->register login登录
    @PostMapping("/user/loginVerification") //没写就是缺省, 任何一个请求 只要匹配不上 就执行该方法
    public Map regOrLogin(@RequestBody Map<String,String> map) {
        String phone = map.get("phone");
        String verificationCode = map.get("verificationCode");
        return userManager.regOrLogin(phone, verificationCode);
    }

    //注册完成个人信息
    @PostMapping("/user/loginReginfo")
    public Map saveUserInfo(@RequestBody UserInfo userInfo) {
        //将token转换成user
        User user = UserHolder.get();
        //存储id
        userInfo.setId(user.getId());
        return userManager.saveUserInfo(userInfo);
    }





    //上传头像
    @PostMapping({"/user/loginReginfo/head","/users/header"})
    public Map uploadHead(MultipartFile headPhoto) throws IOException {
        //将token转换成user
        User user = UserHolder.get();
        //存储id
        return userManager.updateUserInfo(headPhoto, user.getId());
    }

    //查询个人信息    get 请求不需要通过map
    @GetMapping("/users")
    public UserInfoVo findUserInfoById(Long userID,Long huanxinID) {
        if (userID != null) {
            return userManager.findById(userID);
        } else if (huanxinID != null) {
            return userManager.findById(huanxinID);
        } else {
            //将token转换成user
            //User user = findUserByToken(token);
            User user = UserHolder.get();
            return userManager.findById(user.getId());
        }

    }

    //修改用户的个人资料
    @PutMapping("/users")
    public Map updateUserInfoById(@RequestBody UserInfo userInfo) {
        return userManager.updateUserInfoById(userInfo);
    }




   /* //根据token找用户    以后每一次编写代码都要调用一下这个工具类
    public User findUserByToken(String token) {
        //token需要校验
        //1.token是否存在
        //2.token的值是否正确
        //3.解析token
        Map map = JwtUtil.parseToken(token);
        //map转换成user
        User user = BeanUtil.mapToBean(map, User.class, true);
        return user;

    }*/


}
